const express = require('express');
const router = express.Router();
const pool = require('../db/db');

// 获取照片列表
router.get('/photos', async (req, res) => {
    console.log('收到获取照片列表请求');
    try {
        // 首先检查数据库连接
        const client = await pool.connect();
        console.log('数据库连接成功');

        const query = `
            SELECT 
                p.id,
                p.filename,
                p.filepath,
                p.upload_time,
                p.file_size,
                p.tags,
                u.username as uploader
            FROM photos p
            LEFT JOIN users u ON p.user_id = u.id
            ORDER BY p.upload_time DESC
        `;

        console.log('执行查询:', query);
        const result = await client.query(query);
        console.log('查询结果:', result.rows.length, '条记录');

        client.release();

        res.json({
            code: 200,
            data: result.rows,
            message: '获取照片列表成功'
        });
    } catch (error) {
        console.error('获取照片列表失败:', error);
        res.status(500).json({
            code: 500,
            message: '获取照片列表失败: ' + error.message
        });
    }
});

// 添加一个测试路由
router.get('/test', (req, res) => {
    res.json({
        code: 200,
        message: 'API 服务器正常运行'
    });
});

module.exports = router; 